I Lied! The Fastest Csharp Loop Is Even Weirder
作者: Nick Chapsas
标题: I Lied! The Fastest C# Loop Is Even Weirder
笔记: This document explains why a new approach to looping collections in C# is faster than the traditional approach, and how to use it. The new approach involves using a range from 1 to 10, followed by a "while loop" and a "span" to get a reference to the collection. The results of benchmarking this approach were impressive, with the "fast loop" method being 45 nanoseconds for 100 items, and 25 nanoseconds for 10,000 items, which is faster than the "weird faster loop" approach. This approach is not without its risks, as it involves messing with pointers and the user should be careful when using it.
分类: #dotnet #nickchapsas
地址: https://www.youtube.com/watch?v=KLtMtxUihBk
笔记
最快的遍历方式
ref var start = ref MemoryMarshal.GetArrayDataReference(items);
ref var end = ref Unsafe.Add(ref start, items.Length);
while(Unsafe.IsAddressLessThan(ref start, ref end)
{
start.DoSomething();
start = ref Unsafe.Add(ref start, 1);
}
添加时间: April 10, 2023 at 3:22 PM
最适合开发过程的使用依然是 span
var span = Items.AsSpan();
for(var i = 0; i < span.Length; i++)
{
var user = span[i];
user.DoSomething();
}